package tech.yqyl.solo.processor;

import com.google.common.base.Splitter;
import tech.yqyl.StringUtil;
import tech.yqyl.YamlUtils;
import tech.yqyl.solo.BlogInfo;
import tech.yqyl.solo.BlogProcessor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: TitleHeadProcessor
 * @description:
 * @author: caoyangjie
 * @date: 2024/9/16
 **/
public class TitleHeadProcessor extends AbstractProcessor implements BlogProcessor {
    private static Map<String, String> titleMap = new HashMap<>();
    @Override
    public boolean filter() {
        return YamlUtils.getConfig().getLocalStore().isTitleHead();
    }

    @Override
    public void process(BlogInfo blog) {
        if( titleMap.isEmpty() ) {
            synchronized (TitleHeadProcessor.class) {
                if( titleMap.isEmpty() ) {
                    readmeProcessor(blog.getBlogFile());
                }
            }
        }
        if( blog.isReadmeFlag() ) {
            return;
        }
        String fName = blog.getBlogFile().getName();
        String title = titleMap.get(fName);
        blog.getArticle().setArticleTitle(title);
        List<String> contents = Splitter.on("\n").trimResults().omitEmptyStrings().splitToList(blog.getArticle().getArticleContent());
        blog.getArticle().setArticleContent(contents.subList(3,contents.size()-1).stream().collect(Collectors.joining("\n")));
    }

    private void readmeProcessor(File blogFile){
        String readmeFilePath = blogFile.getParentFile().getAbsolutePath().concat(File.separator).concat("README.md");
        try {
            List<String> lines = Files.readAllLines(Paths.get(readmeFilePath));
            for( String line : lines ) {
                if( !(line.contains("[") && line.contains("]") && line.contains("(") && line.contains(")")) ) {
                    continue;
                }
                String oid = StringUtil.find("oid", line).get(0).replaceAll("\\.\\/","");
                String title = StringUtil.find("title", line).get(0);
                titleMap.put(oid, title);
            }
        } catch (IOException e) {
        }
    }
}
